# -*- coding: utf-8 -*-

import arcpy
import glob
import pypinyin
import os
import re
import time

mask = u"E:\\毕设数据\\wuhan_shp\\武汉市土地利用类型\\using_type\\1_耕地.tif"

raw_root = u"E:\\毕设数据\\NDVI\\"

mask_root = u"E:\\毕设数据\\wuhan_shp\\武汉市土地利用类型\\using_type\\"

out_root = u"E:\\毕设数据\\UsingTypeNDVI\\"

ras = u"E:\\毕设数据\\WuhanNDVI\\2000\\2000.02.18-MOD13Q1.A2000049.h27v05.006.2015136104801-wuhan.tif"


def pinyin(word):
    s = ''
    for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
        s += ''.join(i)
    return s


def extract(dir_name, mask, out_path):
    raw = raw_root + dir_name + "\\"
    out = out_path + "\\" + dir_name + "\\"
    if not os.path.exists(out):
        os.makedirs(out)
    rasters = glob.glob(os.path.join(raw, "*.tif"))

    for ras in rasters:
        name = out + ras.split("\\")[-1][:-4] + "-" + pinyin(os.path.basename(out_path)) + ".tif"
        if os.path.exists(name):
            print name + " exist !"
            if re.search("Extract_", name):
                os.remove(name)
                print "remove " + name
            continue
        else:
            out_extract = arcpy.sa.ExtractByMask(ras, mask)
            out_extract.save(name)
            print name + " OK !"


def mask_filter(mask_dir):
    file_path = []
    for i in os.listdir(mask_dir):
        if i.endswith(".tif"):
            file_path.append(os.path.join(mask_dir, i))
    return file_path


def run():
    for i in mask_filter(mask_dir=mask_root):
        dir_name = re.match("(.*)\.tif", os.path.basename(i)).group(1)

        out_dir = os.path.join(out_root, dir_name)
        print out_dir
        # if not os.path.exists(out_dir):
        #     os.makedirs(out_dir)
        for j in range(2000, 2021):
            try:
                extract(str(j), out_path=out_dir, mask=i)
            except:
                continue


if __name__ == "__main__":
    x = time.time()
    run()
    y = time.time()
    cost_time = (y - x) / 60
    print "cost time %.2f min" % cost_time
